package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上报地理位置信息
     * @param userId
     * @param longitude 经度
     * @param latitude  纬度
     * @param address
     * @return
     */
    public Boolean saveAndUpdateLocation(Long userId, Double longitude, Double latitude, String address) {
        try {
            //1.先根据用户id查询UserLocation表
            Criteria criteria = Criteria.where("userId").is(userId);
            Query query = Query.query(criteria);
            UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
            //2.判断用户是否上传过地理位置信息，如果没有，保存；如果有，更新

            if(userLocation == null){
                userLocation = new UserLocation();
                userLocation.setUserId(userId);
                userLocation.setAddress(address);
                userLocation.setCreated(System.currentTimeMillis());
                userLocation.setUpdated(System.currentTimeMillis());
                userLocation.setLastUpdated(System.currentTimeMillis());
                userLocation.setLocation(new GeoJsonPoint(longitude,latitude));

                mongoTemplate.save(userLocation);
            }else{
                //更新地理位置信息
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdate", userLocation.getUpdated())
                        .set("address", address);


                mongoTemplate.updateFirst(query,update , UserLocation.class);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


























    /**
     *搜附近
     */
    public List<Long> queryNearUser(Long userId, Double metre) {

        //1.先查询当前用户id的地理位置信息
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        //2.以当前用户的坐标为圆点
        GeoJsonPoint point = userLocation.getLocation();
        //3.以用户传入的查询距离为半径
        Distance distance = new Distance(metre/1000,Metrics.KILOMETERS);

        //4.构造查询的范围面积
        Circle circle = new Circle(point, distance);

        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);

        //5.查询
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);

        //6.批量获取id
        List<Long> ids = CollUtil.getFieldValues(userLocations, "userId", Long.class);

        return ids;

    }

}